package com.foreknow.controller;

import com.foreknow.model.Guestbook;
import com.foreknow.service.GuestbookService;
import com.foreknow.service.impl.GuestbookServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Web资源的跳转
 * 两种方式
 * 1.请求转发（相当于站内跳转）相当于发送一次请求
 * 2.重定向（站外跳转）
 */
public class AddMessageServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取到请求的参数
        String name = req.getParameter("name");
        String phone = req.getParameter("phone");
        String email = req.getParameter("email");
        String title = req.getParameter("title");
        String content = req.getParameter("content");
        Guestbook gb=new Guestbook();
        gb.setName(name);
        gb.setPhone(phone);
        gb.setEmail(email);
        gb.setTitle(title);
        gb.setContent(content);
        SimpleDateFormat sdf=new SimpleDateFormat("yyy-MM-dd");
        gb.setCreatedtime(sdf.format(new Date()));
        //调用service中的方法save
        GuestbookService service=new GuestbookServiceImpl();
        boolean isRight= service.save(gb);
        if (isRight){
            //请求转发:注意，一定要加上 /
//            req.getRequestDispatcher("/user/get").forward(req,resp);
            //重定向  (可以访问外界链接）
            resp.sendRedirect("/IDEA-javaWebDemo/user/get");
        }else {
            PrintWriter printWriter=resp.getWriter();
            printWriter.println("失败");
        }
    }
}
